package com.moneyhelper.upms.biz;

import com.moneyhelper.common.biz.CommonBiz;
import com.moneyhelper.upms.constant.ContextConstant;
import com.moneyhelper.upms.entity.SysMenu;
import com.moneyhelper.upms.entity.SysRole;
import com.moneyhelper.upms.entity.SysRoleMenu;
import com.moneyhelper.upms.mapper.SysMenuMapper;
import com.moneyhelper.upms.mapper.SysRoleMapper;
import com.moneyhelper.upms.mapper.SysRoleMenuMapper;
import com.moneyhelper.upms.vo.MenuTree;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

/**
 * @author： ygl
 * @date： 2019/07/07
 * @Description：
 */
@Service
public class SysRoleBiz extends CommonBiz<SysRoleMapper, SysRole> {

	@Autowired
	private SysMenuMapper sysMenuMapper;
	@Autowired
	private SysRoleMenuMapper sysRoleMenuMapper;

	/**
	 * 获取角色拥有的资源
	 * @param roleId
	 * @return
	 */
	public List<MenuTree> getRoleHandleMenus(String roleId) {
		List<SysMenu> menus = sysMenuMapper.selectHandleMenusByRoleId(roleId);
		return MenuTree.buildTree(menus, ContextConstant.ROOT);
	}

	/**
	 *  保存角色拥有的菜单
	 * @param roleId
	 * @param menus
	 */
	public void updateRoleMenu(String roleId, String[] menus) {
		// 删除角色对应的菜单权限
		Example example = new Example(SysRoleMenu.class);
		example.createCriteria().andEqualTo("roleId",roleId);
		sysRoleMenuMapper.deleteByExample(example);

		List<SysMenu> menuList = sysMenuMapper.selectAll();
		Map<String, String> map = new HashMap<>();
		for (SysMenu menu : menuList) {
			map.put(menu.getId(), menu.getParentId());
		}
		Set<String> relationMenus = new HashSet<>();
		relationMenus.addAll(Arrays.asList(menus));
		SysRoleMenu sysRoleMenu = null;
		for (String menuId : menus) {
			findParentID(map, relationMenus, menuId);
		}
		for (String menuId : relationMenus) {
			sysRoleMenu = new SysRoleMenu();
			sysRoleMenu.setRoleId(roleId);
			sysRoleMenu.setMenuId(menuId);
			sysRoleMenuMapper.insertSelective(sysRoleMenu);
		}
	}

	/**
	 * 将菜单Id的所有上层父节点id都保存到relationMenus集合中
	 * @param map
	 * @param relationMenus
	 * @param id 菜单ID
	 */
	private void findParentID(Map<String, String> map, Set<String> relationMenus, String id) {
		String parentId = map.get(id);
		if (ContextConstant.ROOT.equals(id) || parentId == null) {
			return;
		}
		relationMenus.add(parentId);
		findParentID(map, relationMenus, parentId);
	}
}
